package com.dk.post.service.impl;

import com.dk.post.dto.UpvoteDTO;
import com.dk.post.service.UpvoteService;
import com.ts.common.core.constant.UpvoteRedisKey;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class UpvoteServiceImpl implements UpvoteService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void add(UpvoteDTO dto) {

        //1.准备点赞的key
        String upvoteKey = String.format(UpvoteRedisKey.UPVOTE_KEY, dto.getType(), dto.getId());
        //查询用户有多少赞的key
        String userKey = String.format(UpvoteRedisKey.USER_UPVOTE_NUM_KEY, dto.getAid());


        //2.判断用户是否对该实体id已经点赞了
        SetOperations<String, String> setOperations = stringRedisTemplate.opsForSet(); //set类型
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        Boolean member = setOperations.isMember(upvoteKey, dto.getUid().toString());
        System.out.println(member);



        if (member) {
            //该用户已经点赞了，取消点赞
            setOperations.remove(upvoteKey,dto.getUid().toString());
            //给实体类对应的作者的赞数减一
            valueOperations.decrement(userKey);
        }else {
            //不在Redis内就实现点赞
            setOperations.add(upvoteKey,dto.getUid().toString());
            //给实体类对应的作者的赞数加一
            valueOperations.increment(userKey);
        }
    }
}
